<template>
  <div class="tinymce-editor">
    <textarea id="tinymceId" :value="content" class="tinymce-textarea" />
    <div class="footer-action">
      <el-button @click="handleCancel()">取消</el-button>
      <el-button type="primary" @click="handleConfirm()">确认</el-button>
    </div>
  </div>
</template>
<script>
import load from '@/views/protocol/tinymce-components/dynamicLoadScript'
import toolbar from '@/views/protocol/tinymce-components/toolbar'
import plugins from '@/views/protocol/tinymce-components/plugins'

const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
export default {
  name: 'TinymceEditor',
  props: {
    contentProps: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      tinymceId: "tinymceId",
      height: 435,
      toolbar: [],
      content: ''
    }
  },
  created() {
    this.content = this.contentProps;
  },
  methods: {
    handleConfirm() {
      this.$emit("submit", this.content);
    },
    handleCancel() {
      this.$emit("cancel");
    },
    init() {
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
      // let id = this.$route.query.id
      // this.$http({
      //   url: this.$http.adornUrl2('/agreement/find'),
      //   method: 'get',
      //   params: this.$http.adornParams({
      //     'id': id,
      //   })
      // }).then(({ data }) => {
      //   this.tableDataLoading = false
      //   let returnData = data.data;
      //   this.title = returnData.title
      //   this.content = returnData.content
      //   this.id = returnData.id
      //   this.createTime = returnData.createTime
      // })
    },
    initTinymce() {
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        images_upload_handler: function(blobInfo, success, failure) {
          var xhr, formData;

          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('POST', "https://admin.huandetai.com/tao/alioss/upload");
          xhr.onload = function() {
            var json;

            if (xhr.status != 200) {
              failure('HTTP Error: ' + xhr.status);
              return;
            }
            json = JSON.parse(xhr.responseText);
            if (json == "" || json == null) {
              failure('Invalid JSON: ' + xhr.responseText);
              return;
            }
            success(json.data);
          };
          formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());
          xhr.send(formData);
        },
        language: 'zh_CN',
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        plugins,
        menubar: this.menubar,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        // Image
        imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.content) {
            editor.setContent(_this.content)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.content = editor.getContent()
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.destroyTinymce()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  }
}
</script>
<style lang="scss">
.tinymce-editor {
  .footer-action {
    display: flex;
    justify-content: flex-end;
    padding: 20px 0 0 0;
  }
}
</style>
